// =====================================================
// FeedList - 订阅源列表（左侧面板）
// =====================================================

import { useState } from "react";
import {
  List,
  Button,
  Modal,
  Form,
  Input,
  message,
  Space,
  Tag,
  App,
} from "antd";
import {
  PlusOutlined,
  ReloadOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import type { Feed } from "../types";
import { addFeed, deleteFeed, refreshFeed } from "../services/feed";

interface FeedListProps {
  feeds: Feed[];
  selectedFeed: Feed | null;
  onSelectFeed: (feed: Feed | null) => void;
  onRefresh: () => void;
}

export default function FeedList({
  feeds,
  selectedFeed,
  onSelectFeed,
  onRefresh,
}: FeedListProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const { modal } = App.useApp();

  // 添加订阅源
  const handleAdd = async (values: {
    url: string;
    title: string;
    category?: string;
  }) => {
    setLoading(true);
    try {
      await addFeed(values);
      message.success("添加成功");
      form.resetFields();
      setIsModalOpen(false);
      onRefresh();
    } catch {
      message.error("添加失败");
    } finally {
      setLoading(false);
    }
  };

  // 刷新单个订阅源
  const handleRefresh = async (feedId: number) => {
    try {
      const result = await refreshFeed(feedId);
      message.success(`刷新成功，新增 ${result.new_articles} 篇文章`);
      onRefresh();
    } catch {
      message.error("刷新失败");
    }
  };

  // 删除订阅源
  const handleDelete = async (feedId: number, feedTitle: string) => {
    modal.confirm({
      title: "确认删除",
      content: `确定要删除"${feedTitle}"吗？删除后将无法恢复。`,
      okText: "确定",
      cancelText: "取消",
      okType: "danger",
      onOk: async () => {
        try {
          await deleteFeed(feedId);
          message.success("删除成功");
          if (selectedFeed?.id === feedId) {
            onSelectFeed(null);
          }
          onRefresh();
        } catch {
          message.error("删除失败");
        }
      },
    });
  };

  return (
    <div style={{ padding: "16px" }}>
      {/* 操作按钮 */}
      <Space style={{ marginBottom: 16, width: "100%" }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setIsModalOpen(true)}
        >
          添加订阅
        </Button>
      </Space>

      {/* 全部文章选项 */}
      <div
        onClick={() => onSelectFeed(null)}
        style={{
          padding: "12px",
          cursor: "pointer",
          background: selectedFeed === null ? "#e6f7ff" : "transparent",
          borderRadius: "4px",
          marginBottom: "8px",
        }}
      >
        📚 全部文章
      </div>

      {/* 订阅源列表 */}
      <List
        dataSource={feeds}
        renderItem={(feed) => (
          <List.Item
            style={{
              padding: "12px",
              cursor: "pointer",
              background:
                selectedFeed?.id === feed.id ? "#e6f7ff" : "transparent",
              borderRadius: "4px",
            }}
            onClick={() => onSelectFeed(feed)}
            actions={[
              <Button
                size="small"
                icon={<ReloadOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  handleRefresh(feed.id);
                }}
              />,
              <Button
                size="small"
                danger
                icon={<DeleteOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  handleDelete(feed.id, feed.title);
                }}
              />,
            ]}
          >
            <List.Item.Meta
              title={
                <Space>
                  {feed.title}
                  {!feed.is_active && <Tag color="red">已停用</Tag>}
                </Space>
              }
              description={feed.category}
            />
          </List.Item>
        )}
      />

      {/* 添加订阅弹窗 */}
      <Modal
        title="添加订阅源"
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        footer={null}
      >
        <Form form={form} onFinish={handleAdd} layout="vertical">
          <Form.Item
            name="url"
            label="RSS 地址"
            rules={[{ required: true, message: "请输入 RSS 地址" }]}
          >
            <Input placeholder="https://example.com/feed.xml" />
          </Form.Item>
          <Form.Item
            name="title"
            label="订阅名称"
            rules={[{ required: true, message: "请输入订阅名称" }]}
          >
            <Input placeholder="例如：阮一峰博客" />
          </Form.Item>
          <Form.Item name="category" label="分类">
            <Input placeholder="例如:科技、编程" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                添加
              </Button>
              <Button onClick={() => setIsModalOpen(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
